﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using THSERP.BaseProvider;
using THSLib;
using THSERP.BusinessEntities;
using System.Transactions;
namespace THSERP.Modules.POS
{
    public partial class guiCombineLocation : THSERPScreen
    {
       // DataSet dsBRPOS = null;
        protected List<GELocationsInfo> LocationList=null;
        protected List<BRPOSLocationsInfo> _lstbRPOSLocationCombine;
        protected THSList<BRPOSItemsInfo> _lstBRPOSItemsCombine;
        protected int _orglocationID;
        protected int _combinelocationID;
        public int OrgLocation
        {
            get { return _orglocationID; }
            set { _orglocationID = value; }
        }
       
        public int CombineLocation
        {
            get { return _combinelocationID; }
            set { _combinelocationID = value; }
        }
        public List<BRPOSLocationsInfo> BRPOSLocationCombineList
        {
            get { return _lstbRPOSLocationCombine; }
            set { _lstbRPOSLocationCombine = value; }
        }
        public THSList<BRPOSItemsInfo> BRPOSItemsCombineList
        {
            get { return _lstBRPOSItemsCombine; }
            set { _lstBRPOSItemsCombine = value; }
        }
        BRPOSsController objBRPOSsController = new BRPOSsController();
        public guiCombineLocation(List<GELocationsInfo> lstLocation, int LocationID)
        {
            
            LocationList = new List<GELocationsInfo>();
            BRPOSLocationCombineList = new List<BRPOSLocationsInfo>();
            BRPOSItemsCombineList = new THSList<BRPOSItemsInfo>();
            LocationList = lstLocation;
            this.OrgLocation = LocationID;
            InitializeComponent();
         
            
        }

        private void guiCombineLocation_Load(object sender, EventArgs e)
        {
            POSEntities entity = (POSEntities)((BaseModuleERP)this.Module).CurrentModuleEntity; 
            fld_dgcBRPOSLocationsCombine.Screen = this;
            fld_dgcBRPOSLocationsCombine.InitializeControl();
            InitialCombineLocation();
            InitialDataToReponsitoryPOS();
            DataSet dsBRPOSs = objBRPOSsController.GetAllByEmployeeAndDate(THSApp.CurrentUsersInfo.FK_HREmployeeID, THSApp.WorkingDate.Date);
            //DataSet ds = new BRPOSLocationsController().GetAllNewByEmployeeAndDateAndLocation(THSApp.CurrentUsersInfo.FK_HREmployeeID, DateTime.Today, iLocation);
            DevExpress.XtraGrid.GridControl grid = entity.BRPOSLocationList.GridControl;
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit reponsitory = (DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit)entity.BRPOSLocationList.GridView.Columns["FK_BRPOSID"].ColumnEdit;
            if (dsBRPOSs != null)
                reponsitory.DataSource = dsBRPOSs.Tables[0];
            grid.RefreshDataSource();
            entity.BRPOSLocationList.GridView.RefreshData();
            //initial POSID reponsitory
           // ths_lkePOSParent.DataSource = dsBRPOS.Tables[0];
           // ths_lkePOSIDChild.DataSource = dsBRPOS.Tables[0];
        }
        public void InitialDataToReponsitoryPOS()
        {
             List<BRPOSsInfo> lst = new List<BRPOSsInfo>();
             DataSet ds = new BRPOSsController().GetAllObjects();
             ths_lkePOSParent.DataSource = ds.Tables[0];
        }
        private void InitialDataToBRPOSItems(int BRPOSID)
        {
            List<BRPOSItemsInfo> list = new List<BRPOSItemsInfo>();

            BRPOSItemsController objBRPOSItemsController = new BRPOSItemsController();
            ICProductsController objICProductsController = new ICProductsController();
            THSList<ICProductsInfo> lstProducts = new THSList<ICProductsInfo>();
            //initial lookupedit
                DataSet ds = objBRPOSItemsController.GetAllDataByForeignColumn("FK_BRPOSID", BRPOSID);
                foreach (DataRow rowItem in ds.Tables[0].Rows)
                {
                    BRPOSItemsInfo objBRPOSItemsInfo = (BRPOSItemsInfo)objBRPOSItemsController.GetObjectFromDataRow(rowItem);
                    if (objBRPOSItemsInfo != null)
                    {
                        ICProductsInfo objICproductsInfo = (ICProductsInfo)objICProductsController.GetObjectByID(objBRPOSItemsInfo.FK_ICProductID);
                        if (objICproductsInfo != null)
                        {
                            if (!lstProducts.Exists("ICProductID", objICproductsInfo.ICProductID))
                                lstProducts.Add(objICproductsInfo);
                        }
                       
                        list.Add(objBRPOSItemsInfo);
                    }
                }

            
            //reponsitory GELocation
            List<GELocationsInfo> listLocation = new List<GELocationsInfo>();
            GELocationsInfo objLocationsInfo = (GELocationsInfo)new GELocationsController().GetObjectByID(OrgLocation);
            listLocation.Add(objLocationsInfo);
            thsRepositoryLookupEdit2.DataSource = listLocation;
            //Reponsitory Products
            thsRepositoryLookupEdit3.DataSource = lstProducts;
            fld_dgcPOSItems.DataSource = list;
            fld_dgvPOSItems.ExpandAllGroups();
        }

        private void InitialCombineLocation()
        {
            DataSet dsGELocations = new GELocationsController().GetLocationByStatus(BusinessObject.DefaultStatus);
            DataSet dsAllLocation = new GELocationsController().GetAllObjects();
            //List<GELocationsInfo> listGELocations = new List<GELocationsInfo>();
            //foreach (DataRow row in dsGELocations.Tables[0].Rows)
            //{
            //    GELocationsInfo obj = (GELocationsInfo)new GELocationsController().GetObjectFromDataRow(row);
            //    if(obj.GELocationParentID>0)
            //        listGELocations.Add(obj);
            //}
            //reponsitory datasource
            lkeGELocationParentID.DataSource = dsAllLocation.Tables[0];
            //Grid soucre
            fld_dgcLocation.DataSource = LocationList;
            fld_dgvLocations.ExpandAllGroups();
        }

        
        private void fld_btnChange_Click(object sender, EventArgs e)
        {

            if (CombineLocation == 0)
            {
                MessageBox.Show("Chưa chọn bàn để gộp! Vui lòng kiểm tra lại.", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            //get locationName by id
            POSEntities entity = (POSEntities)((BaseModuleERP)this.Module).CurrentModuleEntity; 
            String NewLocationName = new GELocationsController().GetObjectNameByID(CombineLocation); 
            BRPOSLocationsController objBRPOSLocationsController = new BRPOSLocationsController();
            BRPOSItemsController objBRPOSItemsController = new BRPOSItemsController();
            BRPOSsController objBRPOSsController = new BRPOSsController();
            List<BRPOSLocationsInfo> lstPOSLocation = new List<BRPOSLocationsInfo>();
            List<BRPOSsInfo> lstBRPOSs = new List<BRPOSsInfo>();
            bool IsCombine = false;
            foreach (BRPOSsInfo obj in (List<BRPOSsInfo>)fld_dgvPOSs.DataSource)
            {
                if (obj.AASelected)
                    lstBRPOSs.Add(obj);
            }
            if (lstBRPOSs.Count == 0)
            {
                MessageBox.Show("Chưa chọn Bill để gộp! Vui lòng kiểm tra lại.", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            ((POSModule)this.Module).ActionEdit();
            foreach (BRPOSsInfo obj in lstBRPOSs)
            {
                //change Location BRPOSLocation
                DataSet dsPOSLocations = objBRPOSLocationsController.GetByPOSIDAndLocationID(obj.BRPOSID,CombineLocation);
                foreach (DataRow row in dsPOSLocations.Tables[0].Rows)
                {
                    BRPOSLocationsInfo objBRPOSLocationsInfo = (BRPOSLocationsInfo)objBRPOSLocationsController.GetObjectFromDataRow(row);
                    BRPOSLocationCombineList.Add(objBRPOSLocationsInfo);
                }
                DataSet dsBRPOSItems = objBRPOSItemsController.GetAllDataByForeignColumn("FK_BRPOSID", obj.BRPOSID);
                foreach (DataRow rowItem in dsBRPOSItems.Tables[0].Rows)
                {
                  BRPOSItemsInfo objItem = (BRPOSItemsInfo)objBRPOSItemsController.GetObjectFromDataRow(rowItem);
                  
                    if (objItem != null)
                    {

                        BRPOSItemsInfo objBRPOSItemsInfo = (BRPOSItemsInfo)entity.ModuleObjects[POSEntities.strBRPOSItemsObjectName];
                        if (!entity.BRPOSItemsList.Exists("FK_ICProductID", objItem.FK_ICProductID))
                        {
                            THSUtil.CopyObjectItems(objItem,objBRPOSItemsInfo,"BRPOSItems");
                            objBRPOSItemsInfo.FK_BRPOSID = 0;
                            entity.UpdateModuleObjectBindingSource(POSEntities.strBRPOSItemsObjectName);
                        }
                        else
                        {
                            int iIndex = entity.BRPOSItemsList.PosOf("FK_ICProductID", objItem.FK_ICProductID);
                            entity.BRPOSItemsList.GridView.FocusedRowHandle = iIndex;
                            POSItemsEntity objCurrent = (POSItemsEntity)entity.BRPOSItemsList.GridView.GetRow(iIndex);
                            objCurrent.BRPOSItemProductQty += objItem.BRPOSItemProductQty;
                            objCurrent.BRPOSItemProductQtyOld = objBRPOSItemsInfo.BRPOSItemProductQty;
                            objCurrent.BRPOSItemQty1 += objItem.BRPOSItemQty1;
                            BRPOSItemsInfo newObject = (BRPOSItemsInfo)objCurrent.SetToBusinessObject("BRPOSItems");
                            entity.ModuleObjects[POSEntities.strBRPOSItemsObjectName] = newObject;
                        }
                        entity.SetValuesAfterValidateProductQty();
                        ((POSModule)this.Module).ClikAddItemToPOSItemsList();
                    }
                }
            }
            using(TransactionScope scope =new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                try
                {
                    foreach (BRPOSLocationsInfo objBRPOSLocationsInfo in BRPOSLocationCombineList)
                    {
                        objBRPOSLocationsController.DeleteObject(objBRPOSLocationsInfo.BRPOSLocationID);
                    }
                    //save 
                    ((POSModule)Module).ActionSaveSeparateCombine();
                    //set current index for gridsearch after remove POS is combined
                    if (((POSModule)Module).Toolbar.ObjectCollectionLength - lstBRPOSs.Count == 1)
                        ((POSModule)Module).Toolbar.CurrentIndex = 0;
                    else
                    ((POSModule)Module).Toolbar.CurrentIndex-=lstBRPOSs.Count;

                    //update location status
                    ((POSModule)Module).UpdateLocationStatus(CombineLocation); 
                    //delete POS combined
                    foreach (BRPOSsInfo objBRPOSsInfo in lstBRPOSs)
                    {
                        objBRPOSsController.DeleteObject(objBRPOSsInfo.BRPOSID);
                    }
                    IsCombine = true;
                    MessageBox.Show("Đã gộp bàn thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                    scope.Complete();

                }catch(Exception ex)
                {
                    MessageBox.Show("Gộp bàn không thành công. Vui lòng kiểm tra lại!","Lỗi",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    scope.Dispose();
                    
                }
            }

        }
        //public String GetNewMainObjectNo(BRPOSsInfo objBRPOSsInfo,String NewLocationName)
        //{
        //    String originalNo = objBRPOSsInfo.BRPOSNo;
        //    String NewObjectNo = NewLocationName;
        //    if (originalNo.Contains("/"))
        //    {
        //        int index = originalNo.IndexOf("/");
        //        NewObjectNo += originalNo.Substring(index, originalNo.Length-index);
        //    }
        //    else
        //        NewObjectNo += String.Format("/{0}", objBRPOSsInfo.BRPOSNo);
        //    return NewObjectNo;
        //}
        private void fld_dgvPOSs_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            BRPOSsInfo objBRPOSsInfo = (BRPOSsInfo)fld_dgvPOSs.GetRow(e.FocusedRowHandle);
            if (objBRPOSsInfo != null)
                InitialDataToBRPOSItems(objBRPOSsInfo.BRPOSID);
        }

        private void fld_dgvPOSs_Click(object sender, EventArgs e)
        {

        }

        private void fld_dgvPOSs_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            BRPOSsInfo objBRPOSsInfo = (BRPOSsInfo)fld_dgvPOSs.GetRow(e.RowHandle);
            if (objBRPOSsInfo != null)
                InitialDataToBRPOSItems(objBRPOSsInfo.BRPOSID);
        }

        private void fld_trlGELocations_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            if (e.Node.HasChildren)
                CombineLocation = 0;
            else
                CombineLocation = Convert.ToInt32(e.Node["GELocationID"].ToString());
        }

        private void fld_btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void fld_dgvLocations_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            BRPOSLocationsController objBRPOSLocationsController = new BRPOSLocationsController();
            BRPOSsController objBRPOSsController =new BRPOSsController();
            List<GELocationsInfo> lst =new List<GELocationsInfo>();
            lst = (List<GELocationsInfo>)fld_dgvLocations.DataSource;
            if (Convert.ToBoolean(e.Value))
            {
                CombineLocation = Convert.ToInt32(fld_dgvLocations.GetRowCellValue(e.RowHandle, colGELocationID));
                for (int i = 0; i <= fld_dgvLocations.RowCount; i++)
                {
                    if (i != e.RowHandle)
                    {
                        fld_dgvLocations.SetRowCellValue(i, colAASelected, false);
                    }
                }
            }
            List<BRPOSsInfo> lstPOS = new List<BRPOSsInfo>();
            DataSet ds = objBRPOSLocationsController.GetAllNewByEmployeeAndDateAndLocation(THSApp.CurrentUsersInfo.FK_HREmployeeID, THSApp.WorkingDate.Date, CombineLocation);
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                BRPOSLocationsInfo objBRPOSLocationsInfo = (BRPOSLocationsInfo)objBRPOSLocationsController.GetObjectFromDataRow(row);
                if (objBRPOSLocationsInfo != null)
                {
                    BRPOSsInfo objBRPOSsInfo = (BRPOSsInfo)objBRPOSsController.GetObjectByID(objBRPOSLocationsInfo.FK_BRPOSID);
                    if (objBRPOSsInfo != null)
                        lstPOS.Add(objBRPOSsInfo);
                }
            }
            fld_dgcPOSs.DataSource = null;
            fld_dgcPOSs.DataSource = lstPOS;
            fld_dgvPOSs.RefreshData();
            fld_dgvLocations.RefreshData();
        }

        private void fld_dgvPOSs_DataSourceChanged(object sender, EventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView gridview = (DevExpress.XtraGrid.Views.Grid.GridView)sender;
            if (gridview != null)
            {
                int iRowHandle = gridview.FocusedRowHandle;
                if (iRowHandle >= 0)
                {
                    BRPOSsInfo objBRPOSsInfo = (BRPOSsInfo)gridview.GetRow(iRowHandle);
                    if (objBRPOSsInfo != null)
                        InitialDataToBRPOSItems(objBRPOSsInfo.BRPOSID);
                }
            }
        }

    }
}